package com.dream.keigezhushou.Activity.acty.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.dream.keigezhushou.Activity.Uiutils.JsonParse;
import com.dream.keigezhushou.Activity.Uiutils.ToastUtils;
import com.dream.keigezhushou.Activity.activity.BaseActivity;

import com.dream.keigezhushou.Activity.url.NetURL;
import com.dream.keigezhushou.R;
import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;

import static okhttp3.MediaType.*;

public class RegestActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.iv_return)
    ImageView ivReturn;
    @BindView(R.id.iv_delete_pass)
    ImageView ivDeletePass;
    @BindView(R.id.btn_get_test)
    Button btnGetTest;
    @BindView(R.id.btn_next)
    Button btnNext;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.et_code)
    EditText etCode;
    private Intent intent;
    private String phoneStr;

    private Timer  timer;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what >= 0){

                btnGetTest.setText("(" + msg.what + ")" + "重新获取");
                btnGetTest.setBackgroundResource(R.drawable.shape_unclick);
                btnGetTest.setClickable(false);
            }else {

                timer.cancel();
                btnGetTest.setText("获取验证码");
                btnGetTest.setBackgroundResource(R.drawable.shape_get);
                btnGetTest.setClickable(true);
            }
        }
    };
    private String passWord;
    private String coded;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regest);
        ButterKnife.bind(this);

        initData();
    }

    //初始化数据
    protected void initData() {

        ivReturn.setOnClickListener(this);
        btnNext.setOnClickListener(this);
        btnGetTest.setOnClickListener(this);
        ivDeletePass.setOnClickListener(this);
    }


    //点击事件的实现

    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.iv_delete_pass:

                etPassword.setText("");
                break;

            case R.id.iv_return:

                //返回
                finish();
                break;

            case R.id.btn_next:

                startRegister();


                break;

            case R.id.btn_get_test:

                getCheckCode();

                break;
        }
    }

    private void getCheckCode() {

        //在获取验证码之前，判断电话号码是否是有效的
        phoneStr = etPhone.getText().toString();
        boolean isPhone = isPhoneNumber(phoneStr);

        Log.i("122","是否到这？");
        if (phoneStr == null || phoneStr.equals("")) {

            ToastUtils.showToast(this, "请输入手机号码");
        } else if (isPhone) {

            OkHttpUtils.post()
                    .url(NetURL.GetCode)
                    .addParams("mobile",phoneStr)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Request request, Exception e) {

                            Log.i("123","是否到这？");
                        }

                        @Override
                        public void onResponse(String response) {

                            //请求成功，按钮发生改变
                            timeThread();

                            Log.i("124","是否到这？");



                        }
                    });



        } else {

            ToastUtils.showToast(this, "请输入正确的手机号码");
        }


    }


    public void startRegister() {

        //密码
        passWord = etPassword.getText().toString();
//        boolean isPassWord = isPassWord(passWord); //密码是否满足要求
//
        coded = etCode.getText().toString();

        Log.i("128","是否到这？");
        OkHttpUtils
                .postString()
                .url(NetURL.REGISTER)
                .content(new Gson().toJson(new User(phoneStr,passWord,coded)))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {

                        Log.i("125",e.getMessage());
                    }

                    @Override
                    public void onResponse(String response) {


                        RegisterResponse message = JsonParse.getFromJson(response,RegisterResponse.class);
                        String strMsg = message.getMessage();
                        String status = message.getStatus();
                        int state = Integer.parseInt(status);

                        if (state == 0){

                            intent = new Intent(RegestActivity.this, RegesitSuccessActivity.class);
                            startActivity(intent);

                            Log.i("mobile",phoneStr);
                            Log.i("password",passWord);
                            Log.i("code",coded);

                            finish();
                        }else {

                            ToastUtils.showToast(RegestActivity.this,strMsg);

                            Log.i("mobile1",phoneStr);
                            Log.i("password1",passWord);
                            Log.i("code1",coded);
                        }
                    }
                });



    }

    //手机号的正则表达判断是否为手机号
    private boolean isPhoneNumber(String phoneStr) {

        String pattern = "(13\\d|14[57]|15[^4,\\D]|17[678]|18\\d)\\d{8}|170[059]\\d{7}";

        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(phoneStr);

        return m.find();
    }


    //密码的正则
    private boolean isPassWord(String passWord) {

        String passRegex = "^[a-zA-Z0-9]{6,12}$";

        Pattern pattern = Pattern.compile(passRegex);
        Matcher matcher = pattern.matcher(passWord);

        return matcher.find();
    }


    private void timeThread() {
        TimerTask task = new TimerTask() {

            int i = 60;
            public void run() {

                mHandler.sendEmptyMessage(i);
                i--;

            }
        };

        timer = new Timer(true);
        timer.schedule(task,0, 1000); //延时1000ms后执行，1000ms执行一次

    }
}
